import React, { useState, useEffect, useRef } from 'react';
import { SafeAreaView, Dimensions, FlatList, StyleSheet, TouchableOpacity, Text, Button, View, Image, ImageBackground, ScrollView, TextInput } from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import { AntDesign } from '@expo/vector-icons';
import * as ImagePicker from 'expo-image-picker';
import { ActionSheet } from 'antd-mobile-rn';
import { Camera } from "expo-camera";
import { Video } from "expo-av";
import { useFocusEffect } from '@react-navigation/native';
import axios from '../../api/axios';
import { useAuth } from '../../context/AuthProvider'
import * as FileSystem from 'expo-file-system';

import AsyncStorage from '@react-native-async-storage/async-storage';
const screenW = Dimensions.get('window').width;

const WINDOW_HEIGHT = Dimensions.get("window").height;

const closeButtonSize = Math.floor(WINDOW_HEIGHT * 0.032);
const captureSize = Math.floor(WINDOW_HEIGHT * 0.09);
const add = (m) => { return m < 10 ? + m : m }
//将时间戳转为普通格式
const fortime = (shijianchuo) => {
    var time = new Date(shijianchuo);
    var y = time.getFullYear();
    var m = time.getMonth() + 1;
    var d = time.getDate();
    var h = time.getHours();
    var mm = time.getMinutes();
    var s = time.getSeconds();
    return y + '-' + add(m) + '-' + add(d) + ' ' + add(h) + ':' + add(mm) + ':' + add(s);
}
const Btn = ({ children, style, color, ...rest }) => {
    return (
        <TouchableOpacity {...rest} style={
            {
                justifyContent: 'center',
                alignItems: 'center',
                ...style
            }
        }>
            <Text style={{ color: color ? color : '#fff' }}>{children}</Text>
        </TouchableOpacity>
    )
}
const AddNews = ({ navigation }) => {
    const { user } = useAuth();
    const [topics, setTopics] = useState([]);
    const [content, setContent] = useState({ content: '' });
    const [newsTopic, setNewsTopic] = useState({ cropsid: '', cropname: '' });
    const [imgView, setImgView] = useState(false);
    const { width, height } = Dimensions.get('window');
    const [hasPermission, setHasPermission] = useState(null);
    // const [imageUrl, setImageUrl] = useState('')
    const [imageUrl, setImageUrl] = useState([])
    const [isShow, setShow] = useState(false)
    const [showCamera, setShowCamera] = useState(1)
    const [clicked, setClicked] = useState('none')
    const [cameraType, setCameraType] = useState(Camera.Constants.Type.back);
    const [isPreview, setIsPreview] = useState(false);
    const [isCameraReady, setIsCameraReady] = useState(false);
    const cameraRef = useRef();
    const [takePic, setTakePic] = useState('')
    const [imglist, setImglist] = useState([])
    const [base64, setBase64] = useState([]);
    // const [imgArr, setImgArr] = useState([])
    const [state, setState] = useState({ imgArr: [] })
    const stateRef = useRef(state)
    const contentRef = useRef(content)
    const newsTopicRef = useRef(newsTopic)
    stateRef.current.state = state
    contentRef.current.content = content
    newsTopicRef.current.cropsid = newsTopic.cropsid
    newsTopicRef.current.cropname = newsTopic.cropname
    var arr = []
    var brr = []
    var base64arr = []
    // 点击参与话题
    const addTopic = (e) => {
        setNewsTopic(() => { return e });
    }
    const addNews = async () => {
        // console.log(contentRef.current.content);
        // console.log(newsTopicRef.current.cropsid);
        // console.log(stateRef.current.state.imgArr);
        // console.log(stateRef.current.state.imgArr.length);
        if (stateRef.current.state.imgArr.length == 0) {
            axios.post('/news/addnews', {
                // newsid,newsimgs,newsimgid自增,userid,newstext,addtime,cropsid,isAudit
                newsid: new Date().getTime() + Math.round(Math.random() * (200 - 1) + 1),
                imgs: [],
                userid: user.userid,
                newstext: contentRef.current.content,
                addtime: new Date().getTime(),
                cropsid: newsTopicRef.current.cropsid
            }).then(res => {
                console.log(res);
                if (res.code == 200) {
                    navigation.navigate('mineNews');
                }
            })
        } else {
            for (let i = 0; i < stateRef.current.state.imgArr.length; i++) {
                console.log(i);
                let base = await FileSystem.readAsStringAsync(stateRef.current.state.imgArr[i], { encoding: 'base64' })
                setBase64([...base64, base])
                base64arr.push(base)
                if (i == stateRef.current.state.imgArr.length - 1) {
                    // console.log(base64arr.length);
                    // console.log(66666666);
                    axios.post('/news/addnews', {
                        newsid: new Date().getTime() + Math.round(Math.random() * (200 - 1) + 1),
                        imgs: base64arr,
                        userid: user.userid,
                        newstext: contentRef.current.content,
                        addtime: new Date().getTime(),
                        cropsid: newsTopicRef.current.cropsid
                    }).then(res => {
                        console.log(res);
                        if (res.code == 200) {
                            navigation.navigate('mineNews');
                        }
                    })
                }
            }
            setTimeout(() => {
                // console.log(8888888);
                base64arr = []
            }, 2000)
        }
    }
    useEffect(() => {
        navigation.setOptions({
            headerBackVisible: false,
            headerRight: () => (
                <Btn
                    style={{
                        width: 69,
                        height: 32,
                        backgroundColor: '#42C05C',
                        borderRadius: 4
                    }}
                    color={'#fff'}
                    onPress={addNews}
                >
                    <Text style={{ fontSize: 16 }}>发布</Text>
                </Btn>
            )
        });
        (async () => {
            const { status } = await Camera.requestPermissionsAsync();
            setHasPermission(status === "granted");
        })();
        axios.get('/news/moretopics')
            .then(res => {
                // console.log(res.data);
                if (res.code == 200) {
                    setTopics(res.data);
                    // console.log(123);
                }
            })

    }, []);
    const onCameraReady = () => {
        setIsCameraReady(true);
    };
    // 点击拍照
    const takePicture = async () => {
        if (cameraRef.current) {
            const options = { quality: 0.5, base64: true, skipProcessing: true };
            const data = await cameraRef.current.takePictureAsync(options);
            const source = data.uri;
            if (source) {
                await cameraRef.current.pausePreview();
                setIsPreview(true);
                setTakePic(source)
            }
        }
    };

    // 翻转摄像头
    const switchCamera = () => {
        if (isPreview) {
            return;
        }
        setCameraType((prevCameraType) =>
            prevCameraType === Camera.Constants.Type.back
                ? Camera.Constants.Type.front
                : Camera.Constants.Type.back
        );
    };

    // 拍照点击×事件
    const cancelPreview = async () => {
        await cameraRef.current.resumePreview();
        setIsPreview(false);
        setShow(false)
    };
    // 拍照点击√事件
    const okPreview = async () => {
        setShow(!isShow)
        setIsPreview(false);
        navigation.navigate('addNews', { imageUrl: [takePic] })
    }

    // 拍照页面上方×和√，点击×取消返回生长日志页，点击√进入detail页面
    const renderCancelPreviewButton = () => (
        <View style={{ justifyContent: 'space-between', flexDirection: 'row', width: '100%' }}>
            <TouchableOpacity onPress={cancelPreview} style={styles.closeButton}>
                <View style={[styles.closeCross, { transform: [{ rotate: "45deg" }] }]} />
                <View
                    style={[styles.closeCross, { transform: [{ rotate: "-45deg" }] }]}
                />
            </TouchableOpacity>
            <TouchableOpacity onPress={okPreview} style={[styles.okButton]}>
                <Text>√</Text>
            </TouchableOpacity>
        </View>
    );

    // 拍照页面底部，翻转按钮以及拍照按钮
    const renderCaptureControl = () => (
        <View style={styles.control}>
            <TouchableOpacity disabled={!isCameraReady} onPress={switchCamera}>
                <Text style={styles.text}>{"翻转"}</Text>
            </TouchableOpacity>
            <TouchableOpacity
                activeOpacity={0.7}
                disabled={!isCameraReady}
                // onLongPress={recordVideo}
                // onPressOut={stopVideoRecording}
                onPress={takePicture}
                style={styles.capture}
            />
        </View>
    );

    if (hasPermission === null) {
        return <View />;
    }

    if (hasPermission === false) {
        return <Text style={styles.text}>No access to camera</Text>;
    }
    const pickImage = async () => {
        let result = await ImagePicker.launchImageLibraryAsync({
            mediaTypes: ImagePicker.MediaTypeOptions.All,
            // allowsEditing: true,
            aspect: [3, 3],
            quality: 1,
            useNativeDriver: true,
            allowsMultipleSelection: true
        });
        if (!result.canceled) {
            for (let i = 0; i < result.assets.length; i++) {
                arr.push(result.assets[i].uri);
            }
            setState({ imgArr: [...stateRef.current.state.imgArr, ...arr] })
            console.log(stateRef.current.state, '是他');
            setImglist((prev) => { return [...prev, ...arr] })
            setImglist([...imglist, ...arr])
            setTimeout(() => {
                arr = []
            }, 2000)
            setIsPreview(false);
        }
    }
    const showActionSheet = () => {
        const BUTTONS = [
            <Text>拍照</Text>,
            <Text onPress={pickImage} >从相册选择</Text>,
            '取消',
        ]
        ActionSheet.showActionSheetWithOptions(
            {
                options: BUTTONS,
                cancelButtonIndex: 2,
            },
            (buttonIndex) => {
                setClicked(BUTTONS[buttonIndex])
                if (buttonIndex == 0) {
                    // pickImage()
                    setShowCamera(2)
                    setShow(!isShow)
                } else if (buttonIndex == 1) {
                    pickImage()
                }
            },
        )
    }
    const deleteImg = (index) => {
        console.log(index);
        console.log('前',stateRef.current.state.imgArr);
        stateRef.current.state.imgArr.splice(index,1);
        console.log('后',stateRef.current.state.imgArr);
        setState({ imgArr: [...stateRef.current.state.imgArr] })
    }
    return (
        <View>
            {
                isShow ?
                    <SafeAreaView style={[{ width: screenW, height: '100%' }]}>
                        <Camera
                            ref={cameraRef}
                            style={[styles.container, { width: screenW, height: '100%' }]}
                            type={cameraType}
                            flashMode={Camera.Constants.FlashMode.on}
                            onCameraReady={onCameraReady}
                            onMountError={(error) => {
                                console.log("cammera error", error);
                            }}
                        />
                        <View style={styles.container}>
                            {isPreview && renderCancelPreviewButton()}
                            {!isPreview && renderCaptureControl()}
                        </View>
                    </SafeAreaView>
                    :
                    <View style={{ height: height - 56, justifyContent: 'space-between' }}>
                        <View onStartShouldSetResponder={() => setImgView(false)}>
                            {/* 导航栏 */}
                            <View style={{
                                backgroundColor: '#fff',
                                flexDirection: 'row',
                                height: 61,
                                alignItems: 'center',
                                borderColor: '#BBBBBB',
                                borderBottomWidth: 1.5,
                            }}>
                                <Ionicons name="logo-firebase" size={26} color="#F98905" style={styles.icon} />
                                <View style={{ flexDirection: 'row', width: '88%' }}>
                                    <FlatList
                                        data={topics}
                                        renderItem={({ item }) => {
                                            return (
                                                <View style={{ flexDirection: 'row' }} key={item.cropsid}>
                                                    <Btn
                                                        style={styles.topBtn}
                                                        color={"#859C48"}
                                                        onPress={() => addTopic(item)}
                                                    >
                                                        {item.cropname}
                                                    </Btn>
                                                </View>)
                                        }}
                                        horizontal={true}
                                        showsHorizontalScrollIndicator={false}
                                    />
                                </View>
                            </View>
                            {/* 文本框 */}
                            <View style={{ justifyContent: 'flex-start', alignItems: 'center', minHeight: 300 }}>
                                <TextInput
                                    style={newsTopic.cropsid ? {
                                        width: '100%',
                                        height: 30,
                                        lineHeight: 25,
                                        color: '#057748',
                                        paddingLeft: 18,
                                        fontSize: 16,
                                    } : { display: 'none' }}
                                    value={'#' + newsTopic.cropname}
                                // onChangeText={text => setNewsTopic(text)}
                                />
                                <TextInput
                                    style={styles.input}
                                    multiline={true}
                                    placeholder="来聊聊吧……"
                                    value={contentRef.current.content.conetnt}
                                    // onChangeText={text => onChangeText(()=>{return text})}
                                    onChangeText={text => setContent(() => { return text })}
                                />
                            </View>
                            <View style={{ width: '100%', maxHeight: WINDOW_HEIGHT * 0.3, flexDirection: 'row' }}>
                                {
                                    stateRef.current.state.imgArr.length >= 0 && stateRef.current.state.imgArr.map((item, index) => {
                                        return (
                                            <ImageBackground source={{ uri: item }} style={{ width: 100, height: 100, marginLeft: 10, alignItems: 'flex-end' }}>
                                                <AntDesign name="closecircleo" size={24} color="#42C08F" onPress={() => deleteImg(index)} />
                                            </ImageBackground>
                                        )
                                    })
                                }
                            </View>
                        </View>
                        {/* 底框 */}
                        <View style={[styles.btm, {}]}>
                            <View
                                onStartShouldSetResponder={() => setImgView(false)}
                                style={{
                                    height: 60, borderBottomColor: '#ddd',
                                    borderBottomWidth: 1.5,
                                    justifyContent: 'center',
                                    alignItems: 'flex-start',
                                    minHeight: 60,
                                }}>
                                <View style={{
                                    backgroundColor: '#DEFBCE',
                                    height: 35,
                                    justifyContent: 'center',
                                    width: 250,
                                    marginLeft: 20,
                                    borderRadius: 20,
                                    alignItems: 'center'
                                }}>
                                    <Text style={{ color: '#42C05C' }}># 参与话题可以增加内容曝光率</Text>
                                </View>
                            </View>
                            <View style={stateRef.current.state.imgArr.length <= 2 ? { paddingTop: 10, minHeight: 60, } : { display: 'none' }}>
                                <AntDesign name="picture" size={38} color="black" onPress={showActionSheet} style={{ left: 20 }} />
                            </View>
                        </View>
                    </View>
            }
        </View>
    )
}
const styles = StyleSheet.create({
    container: {
        ...StyleSheet.absoluteFillObject
    },
    closeButton: {
        // position: "absolute",
        top: 35,
        left: 15,
        height: closeButtonSize,
        width: closeButtonSize,
        borderRadius: Math.floor(closeButtonSize / 2),
        justifyContent: "center",
        alignItems: "center",
        backgroundColor: "#c4c5c4",
        opacity: 0.7,
        zIndex: 2,
    },
    okButton: {
        // position: "absolute",
        top: 35,
        right: 15,
        height: closeButtonSize,
        width: closeButtonSize,
        borderRadius: Math.floor(closeButtonSize / 2),
        justifyContent: "center",
        alignItems: "center",
        backgroundColor: "#c4c5c4",
        opacity: 0.7,
        zIndex: 2,
    },
    media: {
        ...StyleSheet.absoluteFillObject,
    },
    closeCross: {
        width: "68%",
        height: 1,
        backgroundColor: "black",
    },
    control: {
        position: "absolute",
        flexDirection: "row",
        bottom: 38,
        width: "100%",
        alignItems: "center",
        justifyContent: "center",
    },
    capture: {
        backgroundColor: "#f5f6f5",
        borderRadius: 5,
        height: captureSize,
        width: captureSize,
        borderRadius: Math.floor(captureSize / 2),
        marginHorizontal: 31,
    },
    recordIndicatorContainer: {
        flexDirection: "row",
        position: "absolute",
        top: 25,
        alignSelf: "center",
        justifyContent: "center",
        alignItems: "center",
        backgroundColor: "transparent",
        opacity: 0.7,
    },
    recordTitle: {
        fontSize: 14,
        color: "#ffffff",
        textAlign: "center",
    },
    recordDot: {
        borderRadius: 3,
        height: 6,
        width: 6,
        backgroundColor: "#ff0000",
        marginHorizontal: 5,
    },
    text: {
        color: "#fff",
    },
    topBtn: {
        borderWidth: 1,
        borderColor: "#BEC338",
        minWidth: 65,
        height: 32,
        borderRadius: 4,
        marginRight: 2,
        marginLeft: 6,
    },
    icon: {
        width: '12%',
        left: 13
    },
    input: {
        width: '90%',
        minHeight: 40,
        maxHeight: 300,
        color: '#2A5F69',
        // paddingLeft: 26,
        marginTop: 4,
        fontSize: 20,
    },
    btm: {
        width: '100%',
        backgroundColor: '#fff',
    }
});
export default AddNews
